﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using GabageFactory.Models;
using GabageFactory.Utiliy.Crypt;

namespace GabageFactory.Controllers
{
    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        private UserReposity userReposity;

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(new SimpleMembershipProvider()); }

            userReposity = new UserReposity();

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            if (FormsAuthenticationService.HasLogOn())
            {
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, false);
                    User user = (User)HttpContext.Session["currentUser"];
                    if (user.NeedResetPwd)
                    {
                        return RedirectToAction("ChangePassword", "Account");
                    }
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名和密码不匹配，请重新登录");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************
        [Authorize]
        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("LogOn", "Account");
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************
        [Authorize]
        public ActionResult ChangePassword()
        {
            User user = (User)HttpContext.Session["currentUser"];
            if (!user.NeedResetPwd)
            {
                return RedirectToAction("ChangePasswordNotAllowed");
            }
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                User user = (User)HttpContext.Session["currentUser"];
                if (!user.NeedResetPwd)
                {
                    return RedirectToAction("ChangePasswordNotAllowed");
                }
                string oldPwd = model.OldPassword;
                if (string.IsNullOrEmpty(oldPwd) || user.Password != MD5.md5(oldPwd))
                {
                    ModelState.AddModelError("OldPassword", "原始密码不正确，请重新填写.");
                }
                if (string.IsNullOrEmpty(model.NewPassword))
                {
                    ModelState.AddModelError("NewPassword", "请填写新密码.");
                }
                if (string.IsNullOrEmpty(model.ConfirmPassword))
                {
                    ModelState.AddModelError("ConfirmPassword", "请填写确认密码.");
                }
                if (model.NewPassword != model.ConfirmPassword)
                {
                    ModelState.AddModelError("ConfirmPassword", "两次密码输入不正确，请重新填写.");
                }
                User updatedUser = userReposity.GetUserById(user.Id);
                updatedUser.Password = MD5.md5(model.NewPassword);
                updatedUser.NeedResetPwd = false;
                updatedUser.ModifyTime = DateTime.Now;
                userReposity.EditUser(updatedUser);
                HttpContext.Session["currentUser"] = updatedUser;

                return RedirectToAction("ChangePasswordSuccess");
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************
        [Authorize]
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // **************************************
        // URL: /Account/ChangePasswordNotAllowed
        // **************************************
        [Authorize]
        public ActionResult ChangePasswordNotAllowed()
        {
            return View();
        }
    }
}
